﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using STS.Schema.Enums;
using STS.Schema.Interfaces;
using STS.Schema.Base;
using STS.Interfaces;
using STS.Common;
using STS.Schema.MSSql;
using STS.Common.Enums;

namespace STS.Schema
{
    public class DbServer : SqlObjectBase
    {
        private Lazy<ISqlObjectCollection> _databseList;
        internal string _databseName;

        public string ServerVersion { get; internal set; }
        public IDatabase SelectedDatabase
        {
            get
            {
                IDatabase db = _databseList.Value.GetObject<IDatabase>(_databseName);
                if (db == null && _databseList != null && _databseList.Value.Count > 0)
                {
                    db = _databseList.Value.GetObject<IDatabase>(0);
                }
                return db;
            }
        }
        public ProviderType ProviderType { get; internal set; }
        public ConnectionInfo ConnectionInfo { get; private set; }

        public ISqlObjectCollection DatabaseList { get { return _databseList.Value; } }

        public DbServer(string serverName, ConnectionInfo connectionInfo)
            : base()
        {
            Name = serverName;
            ConnectionInfo = connectionInfo;
            _databseList = new Lazy<ISqlObjectCollection>(() =>
            {
                switch (connectionInfo.ProviderType)
                {
                    case ProviderType.MSSql:
                        return GetChildren<MSSqlDatabase>();//.ToGenericCollection<ISqlObjectCollection<IDatabase>, IDatabase>();//.ToSqlObjectCollection<IDatabase>();
                    case ProviderType.MySql:
                        break;
                    case ProviderType.Oracle:
                        break;
                    default:
                        break;
                }
                return null;
            });
        }

        public override ISqlObjectCollection GetChildren<TChild>()// where TChild:class, ISqlObject, new() 
        {
            if (typeof(TChild).GetInterface("IDatabase") != null)
            {
                return this.Factory.GetObjectList<TChild>(null, SqlObjectType.Database);
            }
            return null;
        }

        public override SqlObjectType ObjectType
        {
            get { return SqlObjectType.Server; }
        }
    }
}
